
//globals:
var globalLat;
var globalLng;
var i = 0;
var map;
var geocoder;
var serverURL = "http://trippinoutapp.appspot.com"; //global variable for http request. instaed of localhost 127.0.0.1
//DEPRICATEDvar infowindow = new google.maps.InfoWindow();
var userID;
var accessToken;
var areFriends;

var afterAccept = false;
var onInit = false;

var isAttractionView = true;

google.load('search', '1');

var imageSearch;

var userTrip = {
		id : -1,
		startDate : null,
		endDate : null,
		attrs : []	
	};

var isJustAttendedAttr = false;

var markersArray = [];
var attrStknListIDs = [];

var DEBUG = false;
var tripCandidateForDeletionID = -1;


$(document).ready(function() { /* at some point, all of our code has to go inside this */
	$(".button_class, #search_button, #newTripButton, #attendButton, #chooseDatesButton, #ad_attrAttend, #ad_attrAddPlus, " +
			"#ad_attrAddMinus, #ad_attrAttendees, #newTrip, #attractionView, #sticktNotesView, #shareTrip, #ShowTripOnMap").button();
	
	$("#left_bar_tab_header").tabs({ selected: 2 });
	
		$( "#tab_notifier").click(function() {
			debugAlert("in tab_notifier");
			getAttractionIMayLike();
			getPeopleNearMe();
			getTripSharing();	
		});
	
	
	$("#radio").buttonset({ icons: {primary:'ui-icon-pin-s'}});
	
	$('input:radio[name=view]')[0].checked = true;
	
	
	$("#tab_trip").toggle(true);
	
	$('input:radio[name=view]').click(function() {
 		 var val = ($('input:radio[name=view]:checked').val() == "true") ? true : false;
 		 if(isAttractionView != val) {
 			isAttractionView = val;
 			 removeOverlays();
 			google.maps.event.trigger(map, 'dragend');	
 			$("#accordion1").children().remove();
 			$("#accordion1").html("");		 			 
 			 if(isAttractionView) {
 				debugAlert("attraction view");
				$("#instructions_toggle").html("Click on the map to create an attraction.");
 				$("#tab_trip").toggle(true);
 				$("#tab_notifier").toggle(true);				
 				var hasTrip = (userTrip.id > 0);
 				debugAlert(hasTrip);
 				$("#showTrip").toggle(hasTrip);
 				$("#create_update_trip").toggle(!hasTrip);
 				$("#stickyNoteSpace").toggle(false);
 			 }
 			 else {
 				 debugAlert("sticky note view");
				 $("#instructions_toggle").html("Click on the map to create a sticky note.");
 				 $("#left_bar_tab_header").tabs({ selected: 1 });
 				 $("#tab_notifier").toggle(false);
 				 $("#tab_trip").toggle(false);
 				 $("#showTrip").toggle(false);
 				 $("#create_update_trip").toggle(false);
 				 $("#stickyNoteSpace").toggle(true);
 			 }
 		 }
	});

	
	$("#ad_attrAttend").click(function() {
		var attrId = $(this).data('attrId');
		isJustAttendedAttr = true;
		attendDialog(attrId, showAttractionDetails);
	});
	
	$("#ad_attrAddPlus").click(function() {
		var attrId = $(this).data('attrId');
		debugAlert("adding plus to attraction: " + attrId);
		AttractionAction("addPlusToAttraction", updateAttractionRating, attrId);
	});
	
	$("#ad_attrAddMinus").click(function() {
		var attrId = $(this).data('attrId');
		debugAlert("adding minus to attraction: " + attrId);
		AttractionAction("addMinusToAttraction", updateAttractionRating, attrId);
	});	
	
	$("#ad_attrAttendees").click(function() {
		var attrId = $(this).data('attrId');
		var attendees = $(this).data('attrAttendees');
		debugAlert("clicked attrAttendees for attracrion: " +  key.id);
		debugAlert("calling tr_showAttendees with: " + attendees);
		tr_showAttendees(attendees,true);
	});
	

	$( "#accordion0, #accordion1, #left_notifications" ).accordion({
		collapsible: true,
		fillSpace: true,
		clearStyle: true,
		autoHeight: true,
		navigation: true
	});
	
	$("#editProfileBtn").click(function() {
		getUserProfile(openUserProfileDialog, userID);
	});

	$("#addAttrButton").click(function(){
		$("#add_attr_form").dialog("open");
	});

	$("#schedAttrDateTime").datetimepicker({
		timeFormat: 'hh:mm',
		dateFormat: 'dd/mm/yy',
		minDate: new Date(),
		maxDate: null
	});
	
		$('#attrDuration').timepicker({
		  stepMinute: 30,
		  hourMin: 0,
		  hourMax: 12
	  });

//
//	$( "#slider-range-min" ).slider({
//		range: "min",
//		value: 3,
//		min: 1,
//		max: 80,
//		slide: function( event, ui ) {
//			$( "#amount" ).val( ui.value + " days" );
//			if(($("#from").val()) && ($("#to").val())) {
//				var diffFromToday = 0;
//				var today = new Date();
//				var fromDate = $("#from").datepicker("getDate");
//				if(today.getDate() > fromDate) {
//					diffFromToday = today - fromDate;
//				}
//				else {
//					diffFromToday = fromDate - today + 2;
//				}
//				diffFromToday = parseInt(diffFromToday / 86400000) + $( "#slider-range-min" ).slider("value");
//				//debugAlert("diffFromToday: " + diffFromToday);
//				$("#to").datepicker( "setDate" , diffFromToday);
//			}
//		}
//	});

//	$( "#amount" ).val($( "#slider-range-min" ).slider( "value" ) + " days");
	/*date picker for newTrip*/
	var dates = $( "#from, #to" ).datetimepicker({
		//defaultDate: "+1w",
		changeMonth: true,
		changeYear: true,
		numberOfMonths: 1,
		timeFormat: 'hh:mm',
		dateFormat: 'dd/mm/yy',
		onSelect: function( selectedDate ) {
			var option = this.id == "from" ? "minDate" : "maxDate",
				instance = $( this ).data( "datepicker" ),
				date = $.datepicker.parseDate(
				instance.settings.dateFormat ||
				$.datepicker._defaults.dateFormat,
				selectedDate, instance.settings );
			dates.not( this ).datetimepicker( "option", option, date );
//			if(($("#from").val()) && ($("#to").val())) {
//				debugAlert("setting the slider");
//				var diff = parseInt(($("#to").datepicker( "getDate" ) - $("#from").datepicker( "getDate" )) / 86400000) + 1;
//				debugAlert("to - from: " + diff);
//				$( "#slider-range-min" ).slider("value", diff);
//				$( "#amount" ).val( diff + " days" );
//				$("#slider-range-min").trigger('change');
//			}
		}
	});
	
	var stknDates = $( "#stknFrom, #stknTo" ).datetimepicker({
		//defaultDate: "+1w",
		changeMonth: true,
		changeYear: true,
		numberOfMonths: 1,
		timeFormat: 'hh:mm',
		dateFormat: 'dd/mm/yy',
		onSelect: function( selectedDate ) {
			var option = this.id == "stknFrom" ? "minDate" : "maxDate",
				instance = $( this ).data( "datepicker" ),
				date = $.datepicker.parseDate(
				instance.settings.dateFormat ||
				$.datepicker._defaults.dateFormat,
				selectedDate, instance.settings );
			stknDates.not( this ).datepicker( "option", option, date );
		}
	});


	//callback function to bring a hidden box back
	/*function callback() {
		setTimeout(function() {
			$( "#effect:visible" ).removeAttr( "style" ).fadeOut();
		}, 1000 );
	};*/
	// set effect from select menu value
	$( "#chooseDatesButton" ).click(function() {
		runEffect();
		return false;
	});

	$( "#effect" ).hide();
	
	$( "#dialog-confirm" ).dialog({
			resizable: false,
			height:140,
			modal: true,
			buttons: {
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			}
		});
	
	/* dialog for adding a new attraction*/
	$( "#add_attr_form" ).dialog({
		autoOpen: false,
		modal: true,

		buttons: {
			"Create attreaction": function() {
				if (checkMandatoryField($("#attrTitle")) && checkMandatoryField($("#attrType")) && 
					checkMandatoryFieldInt($("#hourDuration"), false) && 
					checkMandatoryFieldInt($("#minDuration"), true)) {	
						debugAlert("after check in Create attreaction");
						createAttraction();
						$("#add_attr_form").dialog( "close" );
				}
			},
			Cancel: function() {
				$("#attrTitle, #attrType").removeClass( "ui-state-error" );
				clearCreateAttrForm();
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			$("#attrTitle, #attrType").removeClass( "ui-state-error" );
			clearCreateAttrForm();
			$( this ).dialog( "close" );
		}
	});
	
	$("#userAlert").dialog({
		autoOpen: false,
		modal: true,
		width: 300,
		buttons: {
			"OK": function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			$( this ).dialog( "close" );
		}
	});
	
	$("#errorAlert").dialog({
		autoOpen: false,
		modal: true,
		width: 300,
		buttons: {
			"OK": function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			$( this ).dialog( "close" );
		}
	});
	
	
	$( "#add_stkn_form" ).dialog({
		autoOpen: false,
		modal: true,

		buttons: {
			"Create Sticky Note": function() {
				if (checkMandatoryField($("#stknTitle"))) {
					var allowSubmit = true;
					if($("#stknFrom").val() || $("#stknTo").val()) {
						allowSubmit = checkMandatoryField($("#stknFrom")) && checkMandatoryField($("#stknTo"));
					}
					if(allowSubmit) {
						debugAlert("after check in Create sticky note");
						createStickyNote();
						$(this).dialog( "close" );
					}
				}
			},
			Cancel: function() {
				$("#attrTitle, #attrType").removeClass( "ui-state-error" );
				clearCreateStknForm();
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			$("#attrTitle, #attrType").removeClass( "ui-state-error" );
			clearCreateStknForm();
			$( this ).dialog( "close" );
		}
	});
	
	$("#edit_profile_form").dialog({
		autoOpen: false,
		modal: true,
		buttons: {
		"Save and close": function() {
		updateUserProfile();
		$( this ).dialog( "close" );
		},
		Cancel: function() {
			$( this ).dialog( "close" );
		}
	},
	close: function() {
		$( this ).dialog( "close" );
	}
	});

	$( "#deleteTripConfirmation" ).dialog({
		autoOpen: false,
		resizable: false,
		height:140,
		modal: true,
		buttons: {
			"Delete all items": function() {
				destroyUserTrip(tripCandidateForDeletionID);
				$( this ).dialog( "close" );
			},
			Cancel: function() {
				tripCandidateForDeletionID = -1;
				$( this ).dialog( "close" );
			}
		}
	});

	function checkMandatoryField(field, isMinutes) {
		if (field.val().length == 0){
			field.addClass( "ui-state-error" );
			return false;
		}
		field.removeClass( "ui-state-error" );
		return true;
	}
	
	function checkMandatoryFieldInt(field, isMinutes) {
		var error = false;
		if (field.val().length == 0){
			error = true;
		}
		else if(((parseInt(field.val()).toString()) != field.val()) && (("0" + parseInt(field.val()).toString()) != field.val())) {
			error = true;
		}
		else if(parseInt(field.val()) < 0) {
			error = true;
		}
		else if(isMinutes && (parseInt(field.val()) > 59)) {
			error = true;
		}
				
		if( error) {
			field.addClass( "ui-state-error" );
			return false;
		}
		else {
			field.removeClass( "ui-state-error" );
			return true;
		}		
	}
	
	
	function clearCreateAttrForm() {
		$("#attrTitle, #attrDescription, #hourDuration, #minDuration, #attrAddress, #attrUrl").val("");
		$("#attrAttending").attr('checked', true);
		$("#attrType option:first").attr('selected', 'selected');
	}
	
	function clearCreateStknForm() {
		$("#stknTitle, #stknDescription, #stknFrom, #stknTo").val("");
	}
	

	/* For testing purposes only! */
//	$("#attendButton").click(function() {
//		$("#schedule_attr_form").dialog("open");
//	});
	/***********************************************/
	

	/* dialog for attending attraction / scheduling attendance */
	$("#schedule_attr_form").dialog({
		autoOpen: false,
		modal: true,

		buttons: {
			"Attend attraction": function() {
				var attractionId = $(this).data('attrId');
				var date = $("#schedAttrDateTime").val();
				var func = $(this).data('responseFunc');
				debugAlert("attending using schedule_attr_form" );
				if (date.length > 0){
					debugAlert("attending to schedule attraction on " + date);
					$("#schedAttrDateTime").val("");
					isJustAttendedAttr = true;
					createScheduleAttraction(attractionId, func, date);
					
				}
				else {
					$("#schedAttrDateTime").val("");
					isJustAttendedAttr = true;
					tr_attendToAttraction(attractionId);
				}
				$( this ).dialog( "close" );
				$(this).removeData('attrId');
			},
			Cancel: function() {
				$("#schedAttrDateTime").val("");
				$( this ).dialog( "close" );
			}
	},
			close: function() {
				$("#schedAttrDateTime").val("");
				$( this ).dialog( "close" );
			}
		
	});
	
	$( "#attendees_list" ).dialog({
			autoOpen: false,
			height: 500,
			width: 150,
			modal: true,
			position: [300,100],
			close: function() {
				$(this).html("");
				$( this ).dialog( "close" );
			}
		});
	
	$( "#attendee_profile" ).dialog({
		autoOpen: false,
		position: [457,100],
		height: 500,
			width: 310,
			modal: false,
			
			close: function() {
				$(this).html("");
				$( this ).dialog( "close" );
			}
		});
	
	
	$( "#attraction_details" ).dialog({
		autoOpen: false,
		width: 600,
		modal: true,
		
		close: function() {
			$( this ).dialog( "close" );
		}
	});
	
	//eli
	$( "#same_schedule_attractions" ).dialog({
		autoOpen: false,
		height: 600,
		width: 400,
		modal: true,
		
		close: function() {
			$( this ).dialog( "close" );
		}
	});
	$("#attr_search").submit(function() {	
		debugAlert("in $(\"#attr_search\").submit");
		if ($("#address").val().length > 0){
			var search = $("#address").val();
			tr_getGoogle(search);
			$( "#left_bar_tab_header" ).tabs( "select" , 1 );
		}
		return false;
	});

	$("input: button", ".add_attr_form").button();

		
	/*hide/show dates*/
	function runEffect() {
		var options = {};
		$( "#effect" ).show( "bounce", options, 500 );
	};
	
	$("#userBirthday").datepicker({
		dateFormat: 'dd/mm/yy',
		changeMonth: true,
		changeYear: true		
	});
	

	$("#newTripForm").submit(function() {	
		debugAlert("in $(\"#newTripForm\").submit(function() {...}");
		if ($("#newTripName").val().length > 0) {
			debugAlert("creating trip");
			var tripName = $("#newTripName").val();
			var NumOfDays = $("#amount").val();
			var fromDate = $("#from").val();
			var toDate = $("#to").val();
			debugAlert("NumOfDays: " + NumOfDays);			
			var valid = true;
			var time = "";
			if((fromDate != null) && (fromDate != "") && (toDate != null) && (toDate != "")) {
				time = "\"start\" : \"" + fromDate.toString() + "\", \"end\" : \"" + toDate.toString() + "\"";
			}
			/*** This is support for num of days and currently depricated. I'm leaving this code in case we'd want to use it in the future.***/
			/*else if((NumOfDays != null) && (NumOfDays !="")) {
				NumOfDays = parseInt(NumOfDays);
				if(NumOfDays <= 0) {
					errorAlertPopup("please select number of days for the trip or specific dates!");
					valid = false;
				}
				else {
					time = "\"numOfDays\" : " + NumOfDays;
				}				
			}	*/
			else {
				userAlertPopup("Please select specific dates for the trip");
				valid = false;
			}
			
			if(valid) {
				var json = "{\"title\" : \"" + tripName + "\", " + time +"}";
				$( "#left_bar_tab_header" ).tabs( "select" , 0 );
				
				debugAlert("creating trip with json: " + json);
				createTrip(json);
				clearCreateTripForm();
			}
		} else {
			userAlertPopup("Please name your trip first");
		}
		return false;
	});
	
	
	function getAttractionIMayLike(){
		if(userTrip.id > 0) {
			debugAlert("in: getAttractionIMayLike");
			var xmlhttp = createInitialRequest("attractionsYouMayLike",userID, "x-www-form-urlencoded","notification");
			xmlhttp.setRequestHeader("tripId", userTrip.id);
			xmlhttp.onload = getOnReadyStateChangeFunction(showAttrNotification, true,"failed to get attraction I may like");
			xmlhttp.send();	
		}
	}
	
	function showAttrNotification(json){
		debugAlert("Notification type: " + json.type);
		$("#attrNotifications").children().remove();
		$("#attrNotifications").html("");
		for (var i=0; i < json.newNotifications; i++) {
			var attr = json.notifications[i];
			$("#attrNotifications").append('<div class="ui-widget-content1 ui-corner-all">' + 
										   		'<table>' + 
										   			'<tr>' + 
														'<td align="left"><h3>' + attr.title + '</h3><br/></td>' +
														'<td align="right" style="float:right"><h3>' + (attr.pluses - attr.minuses) + '</h3><br/></td>' +
													'<tr>' +
													'<tr>' +
														'<td colspan="2"><a id="tr_attr_notifierAttrDetailsLink' + attr.id + '" href="#"><h5>Show more details</h5></a></td>' +
													'</tr>' +
												'</table>' +
											'</div>');
			//debugAlert("created div fot attr " +  unattendedAttr.id);
			$("#tr_attr_notifierAttrDetailsLink"+attr.id).data('attrID', attr.id).click(function() {
				debugAlert("Attraction " + attr.id + " showMoreDetails clicked!");
				var attrID = $(this).data('attrID');
				getAttractionById(attrID);
			});
			
		}
		if (json.newNotifications == 0) {
			$("#attrNotifications").append('<p>No Attractions Found Based On Your current trip</p>');
		}
	}
	
	function getPeopleNearMe(){
		if(userTrip.id > 0) {
			debugAlert("in: getPeopleNearMe");
			var xmlhttp = createInitialRequest("getUsersNearMe",userID, "x-www-form-urlencoded","notification");
			xmlhttp.setRequestHeader("tripId", userTrip.id);
			xmlhttp.onload = getOnReadyStateChangeFunction(showPeopleNotification, true,"failed to get people near me");
			xmlhttp.send();	
		}
	}
	
	function showPeopleNotification(json){
		debugAlert("Notification type: " + json.type);
		$("#peopleNotifications").children().remove();
		$("#peopleNotifications").html("");
		for (var i=0; i < json.newNotifications; i++) {
			var nearMe = json.notifications[i];
			$("#peopleNotifications").append('<div class="ui-widget-content1 ui-corner-all">' +
                                 				'<table>' + 
								 					'<tr>' +
                                            			'<td><img id="userNearMeProfilePicture' + nearMe.userId + '" alt="Profile Picture" align="left"/></td>' +
                                            			'<td><h3 id="userNearMeName' + nearMe.userId + '"></h3></td>' +
													'</tr>' + 
												'</table>' +
                                    			'<table>' +
													'<tr>' +
          												'<td><h5>Same schedule attractions:</h5></td>' +
          												'<td><h5>' + nearMe.numOfSameScheduleAttractions +'</h5></td>' +
         											'</tr>' +
         											'<tr>' +
                                     					'<td><h5>Not same schedule attractions:</h5></td>' +
          												'<td><h5>' + nearMe.numOfNotSameScheduleAttractions + '</h5></td>' +
         											'</tr>' +
         											'<tr>' +
          												'<td><h5>Not attended schedule attractions:</h5></td>' +
          												'<td><h5>' + nearMe.numOfNotAttendScheduleAttractions + '</h5></td>'  +
         											'</tr>' +
												'</table>' +
                            				'</div>');
			
			tr_getProfileNearMeFB(nearMe.userId);
		}
		if (json.newNotifications == 0) {
			$("#peopleNotifications").append('<p>Currently no users are travelling near you.</p>');
		}
	}
	
	function getTripSharing(){
		debugAlert("in: TripSharing");
		var xmlhttp = createInitialRequest("getTripSharingRequests",userID, "x-www-form-urlencoded","notification");
		xmlhttp.setRequestHeader("tripId", userTrip.id);
		xmlhttp.onload = getOnReadyStateChangeFunction(showTripNotification, true,"failed to get trip sharing");
		xmlhttp.send();	
	}
	
	function showTripNotification(json) {
		debugAlert("Notification type: " + json.type);
		$("#tripNotifications").children().remove();
		$("#tripNotifications").html("");
		for (var i=0; i < json.newNotifications; i++) {
			sharedTrip = json.notifications[i];
			$("#tripNotifications").append('<p><div id="sharedTrip' + sharedTrip.id + '" class="ui-widget-content1 ui-corner-all">'
                                    +'<table width="100%">'
										+'<tr><td><h2>' + sharedTrip.title + '</h2></td>'
										//+'<td align="center" ><input type="button" id="sharedTripDescription' + sharedTrip.sharedEntityId + '" name="sharedTripDescription" value=" Description "/></td></tr>'
                                        +'<tr><td height="15"><h4 id="tripShareFrom" style="color:#30C">From:' + sharedTrip.start + '</h4></td>'
											+'<td><h4 id="tripShareTo" style="color:#30C">To:' +  sharedTrip.end + '</h4></td></tr>'
                                        +'<tr>'
                                            +'<td><img id="tripOwnerProfilePicture' + sharedTrip.requestFromUser + '" alt="Profile Picture" align="left"/></td>'
                                            +'<td><h3 id="tripOwnerName' + sharedTrip.requestFromUser + '"></h3></td></tr>'
                                            									
                                    +'<tr><td align="center" ><input type="button" id="acceptShare' + sharedTrip.sharedEntityId + '" name="acceptShare" value=" Accept "/></td>'
               								+'<td align="center" ><input type="button" id="denyShare' + sharedTrip.sharedEntityId + '" name="denyShare" value=" Deny "/></td>'	
                                        +'</tr></table></div></p>');
			
			$("#sharedTripDescription" + sharedTrip.sharedEntityId).button();
			$("#acceptShare" + sharedTrip.sharedEntityId).button();
			$("#denyShare" + sharedTrip.sharedEntityId).button();
			
			tr_getOwnerTripFB(sharedTrip.requestFromUser);
			
			$("#denyShare" + sharedTrip.sharedEntityId).data("sharedTrip", sharedTrip);
			$("#denyShare" + sharedTrip.sharedEntityId).click(function() {
				debugAlert("in: denyshare");
				 var request = 0;
				 sharingTripRequest($(this).data("sharedTrip"), request);
				});
			
			$("#acceptShare" + sharedTrip.sharedEntityId).data("sharedTrip", sharedTrip);
			$("#acceptShare" + sharedTrip.sharedEntityId).click(function() {
				debugAlert("in: acceptshare");														 
				 var request = 1;
				 sharingTripRequest($(this).data("sharedTrip"), request);
				});
			
			
			
			$("#sharedTripDescription" + sharedTrip.sharedEntityId).data("title",sharedTrip.title);
			$("#sharedTripDescription" + sharedTrip.sharedEntityId).data("requestFromUser",sharedTrip.requestFromUser);
			$("#sharedTripDescription" + sharedTrip.sharedEntityId).data("description",sharedTrip.description);
			$("#sharedTripDescription" + sharedTrip.sharedEntityId).click(function() {
				
					$("#sharedTripDialog").children().remove();
					$("#sharedTripDialog").html('');
				
					$("#sharedTripDialog").append('<table><tr><td><h2>'
												  + $(this).data("title") + '</h2></td></tr>'
												  +'<table><tr>'
		                                            +'<td><img id="tripOwnerProfilePictureDesc' + $(this).data("requestFromUser") + '" alt="Profile Picture" align="left"/></td>'
		                                            +'<td><h3 id="tripOwnerNameDesc' + $(this).data("requestFromUser") + '"></h3></td></tr></table>'
		                                            
												   +'<tr><td><h4>' + $(this).data("description") + '</h4></td></tr></table');	
					tr_getOwnerTripDescFB($(this).data("requestFromUser"));
					
					$("#sharedTripDialog").dialog({
						autoOpen: false,
						modal: true,

						close: function() {
							$( this ).dialog( "close" );
						}

					});
					
					$("#sharedTripDialog").dialog("open");		
					
			});
		}
		if (json.newNotifications == 0) {
			$("#tripNotifications").append('<p>No Trip Share Requests</p>');
		}
	}
	
	function sharingTripRequest(sharedTrip, request) {
		var sharingRequest;
		var isAccept = false;
		if (request == 1){
			sharingRequest = "acceptTripSharingRequest";
			isAccept = true;
		} else {
			sharingRequest = "deniedTripSharingRequest";
		};
		debugAlert("in: TripRequest");
		var xmlhttp = createInitialRequest(sharingRequest,userID, "x-www-form-urlencoded","notification");
		xmlhttp.setRequestHeader("sharingRequestId", sharedTrip.id);
		var responseFunc = sharingTripRequestResponse(isAccept);
		xmlhttp.onload = getOnReadyStateChangeFunction(responseFunc, true,"failed to get trip response");
		xmlhttp.send(); 
	}
	
	function sharingTripRequestResponse(isAccept) {
		 return function(json) {
			debugAlert("in sharingTripRequestResponse return");
			if(isAccept) {
				afterAccept = true;
				getAllUserTrips();
				showTripNotification(json);
			}
			else {
				showTripNotification(json);
			}
		}
	}

	
	function searchComplete() {

		var contentDiv = document.getElementById('ad_attrImg');
		
	    // Check that we got results
	    if (imageSearch.results && imageSearch.results.length > 0) {

	      // Grab our content div, clear it.
	      
	      contentDiv.innerHTML = '';

	      // Loop through our results, printing them to the page.
	      var results = imageSearch.results;

			if (results.length > 0){
				var result = results[0];
				contentDiv.innerHTML = '<img alt="Missing attraction image" src="' + result.tbUrl + '"><br/>powered by <img src="images/google-small-logo.png" alt="Google" align="right">';

			}
	      }
	    else {
	    	contentDiv.innerHTML = 'Image not found';	    	
	    }
	  }
	
	function googleImgSearch(searchTerm, callback) {
		  
	    // Create an Image Search instance.
	    imageSearch = new google.search.ImageSearch();

	    // Set searchComplete as the callback function when a search is 
	    // complete.  The imageSearch object will have results in it.
	    imageSearch.setSearchCompleteCallback(this, callback, null);

	    // Find me a beautiful car.
	    imageSearch.execute(searchTerm);
	    
	    // Include the required Google branding
//	    google.search.Search.getBranding('branding');
	  }

	
	function clearCreateTripForm() {
		$("#newTripName, #amount, #from, #to").val("");
	}
	
	function createTrip(jsonString) {
		var xmlhttp = createInitialRequest("createTrip",userID, "x-www-form-urlencoded","trip");
		var responseFunc = postToWallAndPerformFunc(createTripResponse, "I just created a new trip!", 
			"Want to join me? Enter Trippin' Out and start making new travel buddies!");
		xmlhttp.onload = getOnReadyStateChangeFunction(responseFunc, true,"failed to get create the trip");
		xmlhttp.send(jsonString);		
	}
	

	function createTripResponse(json) {
		var accordion0Content = $('#accordion0').html();
		$('#accordion0').html("");
		$('#accordion0').append(createTripAccordionElemnetTitle(json));
		$('#accordion0').append(createTripAccordionElemnetInfo(json));
		$("#tr_showMoreDetailsLink" + json.id).button();
		$('#accordion0').append(accordion0Content);
		$('#accordion0').accordion('destroy').accordion({
												collapsible: true,
												autoHeight: false,
												navigation: true
											});
		showTrip(json);
	}

		
	function updateTrip(jsonString) {
		var xmlhttp = createInitialRequest("updateTrip",userID, "x-www-form-urlencoded","trip");
		xmlhttp.setRequestHeader("tripId", userTrip.id);
		xmlhttp.onload = getOnReadyStateChangeFunction(updateTripResponse, true,"failed to update the trip");
		xmlhttp.send(jsonString);		
	}
	
	function updateTripResponse(json) {
		if(($('#trip_title_' + key.id).html() != null) && ($('#trip_details_' + key.id).html() != null)) {
			$('#trip_title_' + key.id).html(createTripAccordionElemnetTitleHelper(json));
			$('#trip_title_' + key.id).html(createTripAccordionElemnetInfoHelper(json));
			$('#accordion0').accordion('destroy').accordion({
													collapsible: true,
													autoHeight: false,
													navigation: true
												});
			showTrip(json);
		}		
	}

	window.onload = function() {
		//Google maps
		geocoder = new google.maps.Geocoder();
		var latlng = new google.maps.LatLng(26.745610382199022, -4.21875);
		var myOptions = {
				zoom: 1,
				center: latlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		google.maps.event.addListener(map, 'dragend', function() {
			debugAlert("in google.maps.event.addListener(map, 'dragend', function() {...}");
			var bounds = map.getBounds();
			if (map.getZoom() > 2) {
				debugAlert("bounds were changed!!!!");
				//removeOverlays();
				if(isAttractionView) {
					getLocationAttractions(bounds);
				}
				else {
					getLocationStickyNotes(bounds);
				}
			}

		});
		//google.maps.event.addListener(map, 'idle', scrollZoomChanged);
		//google.maps.event.addListener(map, 'mousedown', scrollZoomChanged);
		google.maps.event.addListener(map, 'click', function(event){
			if (map.getZoom() > 4) {
			globalLat = event.latLng.lat();
			globalLng = event.latLng.lng();
			if(isAttractionView) {
				$("#add_attr_form").dialog("open");
			}
			else {
				$("#stknFrom").datepicker("option", "minDate", new Date());
				$("#stknTo").datepicker("option", "minDate", new Date());
				$("#add_stkn_form").dialog("open");
			}
			}
		});
		
		function scrollZoomChanged() {
			debugAlert("in scrollZoomChanged");
			removeOverlays();
			var bounds = map.getBounds();
			if (map.getZoom() > 2){
				debugAlert("bounds were changed!!!!");
				if(isAttractionView) {
					getLocationAttractions(bounds);
				}
				else {
					getLocationStickyNotes(bounds);
				}				
			}
		}
	}
	
	
	
//	input: json of an attraction
//	this function, given a key - shows its coordinates on the google map.
	function showOnMap(key){
		debugAlert("in showOnMap");
		var pinColor = "7A95FF";
		var colorHover = "000099";
		if (userTrip.attrs.length != 0){
			for (var j = 0; j < userTrip.attrs.length; j++){
				var elemntId = (userTrip.attrs[j].attrId) ? userTrip.attrs[j].attrId : userTrip.attrs[j].id;
				if (elemntId == key.id) {
					pinColor = "75FF47";
					colorHover = "006600";
					break;
				}
			}
		}
			
		var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
				new google.maps.Size(45, 45),
				new google.maps.Point(0,0),
				new google.maps.Point(10, 34));
		var pinShadow = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
				new google.maps.Size(40, 37),
				new google.maps.Point(0, 0),
				new google.maps.Point(12, 35));

		i = i + 1;
		var point = new google.maps.LatLng(key.latitude, key.longitude);
		markersArray[i] = new google.maps.Marker({
			map: map,
			position: point,
			title: key.title.toString(), //eli
			icon: pinImage,
			shadow: pinShadow
		});
		if(isAttractionView) {
			attrStknListIDs[i] = "attraction_" + key.id.toString();
		}
		else {
			attrStknListIDs[i] = "stickyNote_" + key.id.toString();
		}
		
		
		google.maps.event.addListener(markersArray[i], "mouseover", function() {
			var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + colorHover,
					new google.maps.Size(60, 45),
					new google.maps.Point(0,0),
					new google.maps.Point(10, 34));
			this.setIcon(pinImage);

			google.maps.event.addListener(this, "mouseout", function() {
				var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
						new google.maps.Size(60, 45),
						new google.maps.Point(0,0),
						new google.maps.Point(10, 34));
				this.setIcon(pinImage);
			});
		});	
	}


	function validate(f) {
		if(f.address.value=="") {
			return false;
		}
		return true;
	}


//	input: an array of all the markers in the map
//	this function removes all the created markers from the map
	function removeOverlays() {

		if (markersArray) {
			for (i in markersArray) {
				markersArray[i].setMap(null);
			}
			markersArray.length = 0;
			attrStknListIDs.length = 0;
			i = 0;
		}
	}


	function reloadAttrsOrStknsView(json) {
		debugAlert("in reloadAttrsOrStknsView - getting the bounds");
		var bounds = map.getBounds();
		debugAlert("in reloadAttrsOrStknsView - got the bounds " + bounds);
		if(isAttractionView) {
			getLocationAttractions(bounds);
			
			if(isJustAttendedAttr) {
				getUserTrip(userTrip.id);
				isJustAttendedAttr = false;
			}
		}
		else {
			getLocationStickyNotes(bounds);
		}
	}


//	input: id of attraction the user wants to attend 
//	output: json of the attraction after the user attended
	function tr_attendToAttraction(attractionId) {
		if(userTrip.id <= 0) {
			userAlertPopup("Please create a trip before you attend to attractions");
		}
		else {
			var xmlhttp = createInitialRequest("attendToAttraction", userID, 
					"x-www-form-urlencoded","attraction");
			xmlhttp.setRequestHeader("attractionId", attractionId.toString());
			xmlhttp.setRequestHeader("tripId", userTrip.id);

			var responseFunc = postToWallAndPerformFunc(reloadAttrsOrStknsView, "I just attended an attraction!", 
					"Want to join me? Enter Trippin' Out and start making new travel buddies!");
			xmlhttp.onload = getOnReadyStateChangeFunction(responseFunc, true, "faild to attend to attraction ");

			xmlhttp.send();	
		}
	}
	
	function postToWallAndPerformFunc(func, postString1, postString2) {
		return function(json) {
			debugAlert("should post to FB with - " + json.title);
			postToFeed(postString1 + " (" + json.title + ")", postString2);
			func(json);
		};
	}


	function createAttraction() {
		debugAlert("in createAttraction");
		
		var json = "{\"title\" : " + "\"" + $("#attrTitle").val() + "\"" + ", " + 
		"\"description\" : " + "\"" + $("#attrDescription").val() + "\"" + ", " +
		"\"type\" : " + "\"" + $("#attrType").val() + "\"" + ", " +
		"\"duration\" : {" +
		"					\"hours\" : " + parseInt($("#hourDuration").val()) + ", " +
							"\"minutes\" : " + parseInt($("#minDuration").val()) + 
						"}, "+
		"\"primaryPhoneNumber\" : " + "\"" + $("#attrPrimaryPhone").val() + "\"" + ", " +
		"\"address\" : " + "\"" + $("#attrAddress").val() + "\"" + ", " +
		"\"website\" : " + "\"" + $("#attrUrl").val() + "\"" + ", " +
		"\"email\" : " + "\"" + $("#attrEmail").val() + "\"" + ", " +
		"\"latitude\" : " + globalLat.toString() + ", " + 
		"\"longitude\" : " + globalLng.toString() + "}";

		debugAlert("json to send: " + json);

		debugAlert("user ID is " + userID);
		var xmlhttp = createInitialRequest("createAttraction",userID,"json","attraction");

		xmlhttp.onload = getOnReadyStateChangeFunction(reloadAttrsOrStknsView, true, "faild to create attraction");

		debugAlert("sending the request");
		xmlhttp.send(json);	
		
		clearCreateAttrForm();		
	}

	
	function createStickyNote() {
		debugAlert("in createStickyNote");
		var start = $("#stknFrom").val() ? "\"start\" : \"" + $("#stknFrom").val() + "\"" + ", " : "";
		var to = $("#stknTo").val() ? "\"end\" : \"" + $("#stknTo").val() + "\"" + ", " : "";
		
		var json = "{\"title\" : " + "\"" + $("#stknTitle").val() + "\"" + ", " + 
		"\"description\" : " + "\"" + $("#stknDescription").val() + "\"" + ", " +
		start + to +
		"\"latitude\" : " + globalLat.toString() + ", " + 
		"\"longitude\" : " + globalLng.toString() + "}";

		debugAlert("json to send: " + json);

		debugAlert("user ID is " + userID);
		var xmlhttp = createInitialRequest("createStickyNote",userID,"json","stickyNote");

		xmlhttp.onload = getOnReadyStateChangeFunction(reloadAttrsOrStknsView, true, "faild to create sticky note");

		debugAlert("sending the request");
		xmlhttp.send(json);	
		
		clearCreateStknForm();		
	}

	
	function  createScheduleAttraction(attractionId, func, attrDate) {
		debugAlert("in createScheduleAttraction");
		if(userTrip.id < 0) {
			userAlertPopup("please create a trip before you attend to attractions");
		}
		else {
			var json = "{\"startTime\" : " + "\"" + attrDate + "\"}";
			debugAlert("creating schedule attr with json: " + json);
			
			var xmlhttp = createInitialRequest("createScheduleAttraction",userID,"json","scheduleAttraction");
			xmlhttp.setRequestHeader("attractionId", attractionId);
			xmlhttp.setRequestHeader("tripId", userTrip.id);

			xmlhttp.onload = getOnReadyStateChangeFunction(func, true, "faild to create schedule attraction");
			xmlhttp.send(json);
		}
	}

	
	function attendDialog(attrId, func){
		debugAlert("in attendDialog");
		$("#schedule_attr_form").removeData('attrId');
		$("#schedule_attr_form").removeData('responseFunc');
		
		var responseFunc = postToWallAndPerformFunc(func, "I just attended an attraction!", 
			"Want to join me? Enter Trippin' Out and start making new travel buddies!");
		$("#schedule_attr_form").data('attrId', attrId);
		$("#schedule_attr_form").data('responseFunc',responseFunc);
		$("#schedule_attr_form").dialog("open");
	}
	

	function showAttractionDetails(json) {
		debugAlert("in showAttractionDetails");
		createAttractionGeneralInfo(json);
		createAttractionPastFutureSchedule(json);
		$( "#attraction_schedules_tab_header" ).tabs({ selected: 1 });
		$("#ad_attrImg").html("Loading...");
		$("#attraction_details").dialog("open");
		
		if(isJustAttendedAttr) {
			isJustAttendedAttr = false;
			getUserTrip(userTrip.id);			
			reloadAttrsOrStknsView(json);			
		}
	}

	
	function createAttractionGeneralInfo(key) {
		$("#ad_attrAttendees").removeData('attrAttendees');
		$("#ad_attrAttendees").removeData('attrId');
		$("#ad_attrAttend").removeData('attrId');
		$("#ad_attrAddPlus").removeData('attrId');
		$("#ad_attrAddMinus").removeData('attrId');

		var rating = (parseInt(key.pluses) - parseInt(key.minuses));
		//var desc = splitStringToRows40Long(key.description);

		debugAlert(" the desc is :" + key.description);
		$("#ad_attrTitle").html(key.title);
		$("#ad_attrRating").html(rating);
		$("#ad_attrType").html(key.type);
		$("#ad_attrDescription").html(key.description);
		var hours;
		var minutes;
		if (key.duration.hours < 10) {
			hours = "0" + key.duration.hours;
		}else {
			hours = key.duration.hours;
		}
		if (key.duration.minutes < 10) {
			minutes = "0" + key.duration.minutes;
		}else {
			minutes = key.duration.minutes;
		}
		$("#ad_attrDuration").html(hours + ":" + minutes);
		$("#ad_attrAddress").html(key.address);
		$("#ad_attrPrimaryPhoneNumber").html(key.primaryPhoneNumber);
		$("#ad_attrWebsite").html(key.website);
		$("#ad_attrEmail").html(key.email);
		googleImgSearch(key.title, searchComplete);
		
		/**Set listeners for attraction's details (inner html)*/
		var attendees = allAttrAttendeesNoPast(key);
		
		$("#ad_attrAttendees").data('attrAttendees', attendees);
		$("#ad_attrAttendees").data('attrId', key.id);
		$("#ad_attrAttend").data("attrId", key.id);	
		$("#ad_attrAddPlus").data('attrId', key.id);
		$("#ad_attrAddMinus").data('attrId', key.id);
		
	}
	
	function allAttrAttendeesNoPast(attr) {
		var attendees = [];
		attendees = attendees.concat((attr.futureAttendees != null) ? attr.futureAttendees : []);
		var notScheduledYetAttendees = (attr.notScheduledYetAttendees != null) ? attr.notScheduledYetAttendees : [];
		for(var i = 0; i < notScheduledYetAttendees.length; i++) {
			if($.inArray(notScheduledYetAttendees[i], attendees) < 0) {
				attendees.push(notScheduledYetAttendees[i]);
			}
		}
		return attendees;
	}

	
	function updateShortAttractionRating(key) {
		var rating = (parseInt(key.pluses) - parseInt(key.minuses));
		$("#at_attrRating" + key.id).html('<h2>' + rating + '</h2>');
	}
	
	
	function updateAttractionRating(key) {
		var rating = (parseInt(key.pluses) - parseInt(key.minuses));
		$("#ad_attrRating").html('<h2>' + rating + '</h2>');
		updateShortAttractionRating(key);
	}
	
	function AttractionAction(action, func, attrID) {
		var xmlhttp = createInitialRequest(action ,userID, "x-www-form-urlencoded","attraction");
		xmlhttp.setRequestHeader("attractionId", attrID);
		xmlhttp.setRequestHeader("tripId", userTrip.id);
		xmlhttp.onload = getOnReadyStateChangeFunction(func, true, "failed to get the updated attraction");
		xmlhttp.send();
	}

	
	function createAttractionPastFutureSchedule(key) {
		debugAlert("in createAttractionPastFutureSchedule");
		$("#future_schedule_attractions_table").children().remove();
		$("#future_schedule_attractions_table").html("");
		for(var i = 0; i < key.futureScheduledAttractions.length; i++) {
			var scheduleAttr = key.futureScheduledAttractions[i];
			createScheduleAttrDisplay(true,scheduleAttr);
		}
		
		
		$("#past_schedule_attractions_table").children().remove();
		$("#past_schedule_attractions_table").html("");
		for(var j = 0; j < key.pastScheduledAttractions.length; j++) {
			var scheduleAttr = key.pastScheduledAttractions[j];
			createScheduleAttrDisplay(false,scheduleAttr);
		}
	}
	
	
	function scheduleAttractionAction(action, func, key) {
		isJustAttendedAttr = true;
		debugAlert("in scheduleAttractionAction. going to " + action + " with id " + key.id + " attrId " +  key.attrId);
		var xmlhttp = createInitialRequest(action ,userID, "x-www-form-urlencoded","scheduleAttraction");
		xmlhttp.setRequestHeader("tripId", userTrip.id);
		xmlhttp.setRequestHeader("attractionId", key.attrId);
		xmlhttp.setRequestHeader("scheduleAttractionId", key.id);
		xmlhttp.onload = getOnReadyStateChangeFunction(func, true, "failed to get the updated attraction");
		xmlhttp.send();
	}
	
	
	function createScheduleAttrDisplay(isFuture, key) {
		var schAttrId = key.id;
		debugAlert("in createScheduleAttrDisplay");
		var attendButtonHTML = '<td></td>';
		var scheduleHtmlString = isFuture ? 'is scheduled ' : 'was ';
		scheduleHtmlString = 'this attraction ' + scheduleHtmlString + 'on ' + key.startTime;
		var scheduleHtml = '<td><p>' + scheduleHtmlString + '</p></td>';
		
		var isInTripSchedule = false;
		var scheduleAttrDateStart = createDateIncludeTimeFromString(key.startTime);
		var scheduleAttrDateEnd = createDateIncludeTimeFromString(key.startTime);
		if((scheduleAttrDateStart >= userTrip.startDate) && (scheduleAttrDateEnd <= userTrip.endDate)) {
			isInTripSchedule = true;
		}
		debugAlert(scheduleAttrDateStart + " >= " + userTrip.startDate + " return: " + (scheduleAttrDateStart >= userTrip.startDate) + "\n" +
				scheduleAttrDateEnd + " <= " + userTrip.endDate + " return: " + (scheduleAttrDateEnd <= userTrip.endDate) + "\n" + 
				"therefor isInTripSchedule == " + isInTripSchedule);
		
		var attendees = (key.attendees != null) ? key.attendees : [];
		debugAlert(attendees + " attendees are attenddeing schedule attr " + schAttrId);
		var attendeesNum =  attendees.length;
		var attendeesString = (attendeesNum != 1) ? (attendeesNum + " attendees") : "1 attendee";
		var attendeesHtml = '<td><a id="sa_attendees_list_link' + key.id + '" href="#">' + attendeesString + '</a></td>';
				
		var isAttended = false;		
		if(isFuture && isInTripSchedule) {
			debugAlert("checking if " + userID + " is attendded to schedule attr " + schAttrId);
			for(var i = 0; i < attendeesNum; i++) {
				debugAlert("attendees[" + i + "] == " + attendees[i]);
				if(attendees[i] == userID) {
					isAttended = true;
					break;
				}
			}
			
			if(!isAttended) {
				debugAlert("user " + userID + " is not attendded to schedule attr " + schAttrId);
				attendButtonHTML = '<td align="center"><input type="button" id="sa_attrAttend' + schAttrId + '" name="attrAttend" value="Attend"/></td>';
				debugAlert("attendButtonHTML: " + attendButtonHTML);
			}
			else {
				debugAlert("user " + userID + " is attendded to schedule attr " + schAttrId);
				attendButtonHTML = '<td align="center"><input type="button" id="sa_attrUnAttend' + schAttrId + '" name="attrUnAttend" value="Unattend"/></td>';
			}
		}

		
		var tr = '<tr>' + scheduleHtml + attendeesHtml + attendButtonHTML + '</tr>';
		debugAlert("creating a schedule row for schedule attr " + schAttrId + ": " + tr);
		if(isFuture) {
			$("#future_schedule_attractions_table").append(tr);
		}
		else {
			$("#past_schedule_attractions_table").append(tr);
		}
		
		//link and button listeners:
		if(isFuture) {
			if(!isAttended) {
				$("#sa_attrAttend" + schAttrId).button();		
				$("#sa_attrAttend" + schAttrId).click(function() {
					debugAlert("in #sa_attrAttend" + schAttrId + " button");
					var responseFunc = postToWallAndPerformFunc(showAttractionDetails, "I just attended an attraction!", 
						"Want to join me? Enter Trippin' Out and start making new travel buddies!");
					scheduleAttractionAction("attendToScheduleAttraction", responseFunc, key);
				});
			}
			else {
				$("#sa_attrUnAttend" + schAttrId).button();		
				$("#sa_attrUnAttend" + schAttrId).click(function() {
					scheduleAttractionAction("unattendFromScheduleAttraction", showAttractionDetails, key);
				});
			}
		}
				
		$("#sa_attendees_list_link" + schAttrId).click(function() {
			debugAlert("clicked attrAttendees for attracrion: " +  schAttrId);
			debugAlert("calling tr_showAttendees with: " + attendees);
			tr_showAttendees(attendees,true);
		});
	}
	

	/**
	 * "My Trips": lists all trips
	 */
	function doOnTab0(json) {		
		debugAlert("in doOnTab0");
		$("#accordion0").children().remove();
		$("#accordion0").html("");
		for (var i=0; i < json.size; i++) {
			key = json.data[i];

			$('#accordion0').append(createTripAccordionElemnetTitle(key));
			$('#accordion0').append(createTripAccordionElemnetInfo(key));

			$("#tr_showMoreDetailsLink" + key.id).button();
			$("#tr_showMoreDetailsLink" + key.id).data("tripId", key.id).click(function() {
				var tripId = $(this).data("tripId");
				debugAlert("Trip " + tripId + " showMoreDetails clicked!");
				userTrip.id = tripId;
				getUserTrip(tripId);
			});
			
			if($("#sharedWith_" + key.id).html()) {
				var sharedWith = getSharedWithArray(key);
				$("#sharedWith_" + key.id).data("sharedWith", sharedWith).click(function() {
					var usersSharedWith = $(this).data("sharedWith");
					debugAlert("in #sharedWith_" + key.id + ". the users are: " + usersSharedWith);
					tr_showAttendees(usersSharedWith,false);
				});
			}
			
			$("#deleteTrip_" + key.id).data("tripID", key.id).data("tripTitle", key.title).click(function() {
				var tripTitle = $(this).data("tripTitle");
				var tripId = $(this).data("tripID");
				debugAlert("Trip " + tripId + " with title: " + tripTitle + " deleteTrip clicked!");
				tripCandidateForDeletionID = tripId;
				$("deleteTripName").html(tripTitle);
				$("#deleteTripConfirmation").dialog("open");
			});
			
		}
	
		$('#accordion0').accordion('destroy').accordion({
												collapsible: true,
												autoHeight: false,
												navigation: true
											});
		
		if((json.size > 0) && !afterAccept) {
			userTrip.id = json.data[0].id;
			getUserTrip(userTrip.id);	
		}
		else if(json.size == 0) {
			$("#create_update_trip").toggle(true);
			$("#showTrip").toggle(false);
		}
		afterAccept = false;
	}
	
	
	function createTripAccordionElemnetTitle(key) {
		return '<h3 id="trip_title_' + key.id + '">' + createTripAccordionElemnetTitleHelper(key) + '</h3>';
	}
	
	function createTripAccordionElemnetTitleHelper(key) {
		return '<a href="#">' +  key.title + '</a>';
	}
	
	function createTripAccordionElemnetInfo(key) {	
		return '<div id="trip_details_' + key.id + '">' + createTripAccordionElemnetInfoHelper(key) + '</div>';
	}
	
	function createTripAccordionElemnetInfoHelper(key) {
		var numOfDays = parseInt(key.numOfDays);
		var start = key.start;
		var end = key.end;
		var time = "";		
		if((start != null) && (start != undefined) && (end != null) && (end != undefined)) {
			time = start + " - " + end + "<br/>";
		}
		
		var sharedWith = getSharedWithArray(key);
		var shareTr = "";
		if(sharedWith.length > 0) {
			var users = (sharedWith.length == 1) ? " user" : " users";
			shareTr = '<tr><td><a href="#" id="sharedWith_' + key.id + '">This trip is shared with ' + sharedWith.length + users + '</a></td></tr><tr><td><br/></td></tr>';
		}
		
		time = time + numOfDays + " days";
		var element = '<p>' +
						'<table>' +
							'<tr>' +
								'<td width="243">' + time + '</td>' +
							'</tr>'+
							'<tr><td><br/></td></tr>' +
							shareTr + 
							'<tr>' +
								'<td width="131">' +
									'<input type="button" id="tr_showMoreDetailsLink' + key.id + '" value="Show Trip details"/>' + 
								'</td>' +
							'</tr>' +
						'</table>' +
						'<a href="#" id="deleteTrip_' + key.id + '" style="float:right;"><img src="images/trash.png" height="35" width="35" /></a>' +
					'</p>';
		return element;
	}
	
	function getSharedWithArray(key) {
		var sharedWith = [];
		var index = 0;
		if(key.userId != userID) {
			sharedWith[index] = key.userId;
			index++;
		}
		if(key.sharedWith) {
			for(var i = 0; i < key.sharedWith.length; i++) {
				if(key.sharedWith[i] != userID) {
					sharedWith[index] = key.sharedWith[i];
					index++;
				}
			}
		}
		return sharedWith;
	}
	
	/**
	 * "Search Results": lists all attractions searched map location
	 */
	function doOnTab1(json) {
		debugAlert("in doOnTab1");
		$("#accordion1").children().remove();
		$("#accordion1").html("");
		if(isAttractionView) {
			for (var i=0; i < json.size; i++) {
				key = json.data[i];
				showOnMap(key);
				showShortAttractionHelper(key);

				$("#at_rateAdd" + key.id).button();
				$("#at_rateSub" + key.id).button();
				$("#at_attendButton" + key.id).button();
			}
		}
		else {
			debugAlert("getting all sticky notes");
			for (var i=0; i < json.size; i++) {
				key = json.data[i];
				showOnMap(key);
				showShortStickyNote(key);
			}
			
		}
		
		$("#accordion1").accordion('destroy').accordion({
												collapsible: true,
												autoHeight: false,
												navigation: true
											});
		
		$("#accordion1 h3").mouseout(function() {
			mouseOverOut(this,"mouseout");
		});
		
		$("#accordion1 h3").mouseover(function() {
			mouseOverOut(this,"mouseover");
		});
		
		$( "#left_bar_tab_header" ).tabs({ selected: 1 });		
	}
	
	
	function mouseOverOut (element,event) {
		//debugAlert("in $(#accordion0 h3)." + event);	
		for(var j = 1; j < attrStknListIDs.length; j++) {
			if(('acc0_h3_' + attrStknListIDs[j]) == element.id) {
				google.maps.event.trigger(markersArray[j], event);
				break;
			}				
		}		
	}
	
	function showShortStickyNote(key) {
		debugAlert("in showShortStickyNote of " + key.id);
		
		var fullDesc = key.description;
		//var desc = shortDescriptionToLines(fullDesc);
	
		
		var stknUser =  key.userId;
		var stknId = key.id;
		var time = "";
		if((key.start != null) &&(key.start != "") && (key.end != null) && (key.end != "")) {
			time = 'on ' + key.start + " - " + key.end;
		}
		
		$('#accordion1').append('<h3 id="acc0_h3_stickyNote_' + stknId + '"><a href="#">' + key.title + '</a></h3>' + 								
				'<div id="acc0_div_attraction_' + stknId + '">' + 
					'<p>' +
						'<table style="margin: 5px;">' +
							'<tr>' +
								'<td id="shortStknCreatorPic_' + stknId + '_' + stknUser + '" rowspan="2"></td>' +
								'<td id="shortStknCreatorNameLink_' + stknId + '_' + stknUser + '" align="left" valign="middle"></td>' +
							'</tr>'+
							'<tr>' + 
								'<td id="mutualFriends' + stknId + '_' + stknUser + '" align="left" valign="middle"></td>' + 
							'</tr>' +
							'<tr>' +
								'<td colspan="2"><br/><p>is looking for travelling partners ' + time + '</p><br/><br/></td>' +
							'</tr>' +
							'<tr>' +
								'<td colspan="2" title="' + fullDesc + '" align="left">' + fullDesc + '</td>' +
							'</tr>'+
						'</table>' +
					'</p>' +
				'</div>');
		
		debugAlert("user " + stknUser + " image is added");
		FB.api( 
				{ 
					method: 'fql.query', 
					query: 'SELECT uid,profile_url,pic_square,first_name,last_name,mutual_friend_count FROM user WHERE uid='+ stknUser 
				}, 

				function(response) {
					debugAlert("getting the FB response for the creator of the sticky note");
					$('#shortStknCreatorPic_' + stknId + '_' + stknUser).html('<img src=' + response[0].pic_square + '/>');
					debugAlert("getting the FB user name: " + response[0].first_name + " " + response[0].last_name);
					$('#shortStknCreatorNameLink_' + stknId + '_' + stknUser).html('<a href="#" id="stknUser_' + stknUser + '_' + stknId + '">' +
							response[0].first_name + " " + response[0].last_name + '</a>');
					
					if (response[0].uid != userID){
						var mutualFriends = response[0].mutual_friend_count;
						isFriend(response[0].uid);
						if (areFriends == true) {
							$('#mutualFriends' + stknId + '_' + stknUser).html('<p>(You are friends)</p>');
						}
						else if (mutualFriends == 0){
							$("#shortStknCreatorNameLink_" + stknId).attr('rowspan', 2);
						}
						else if (mutualFriends == 1){
							$('#mutualFriends' + stknId + '_' + stknUser).html('<p>(One mutual friend)</p>');
						}
						else {
							$('#mutualFriends' + stknId + '_' + stknUser).html('<p>(' + mutualFriends + ' mutual friends)</p>');
						}
					}
					
					$('#stknUser_' + stknUser + '_' + stknId).data('userid', stknUser).click(function() {
						var uid = $(this).data('userid');
						debugAlert('user (' + stknUser + ') link was clicked');
						getUserProfile(displayAttendeeProfile, uid);
					});
				}
		); 

	}
	
	


	function showShortAttractionHelper(key) {
		debugAlert("in showShortAttractionHelper of " + key.id);
		var attendees = allAttrAttendeesNoPast(key);
		var numOfAttendees = attendees.length;
				
		var attendeesLink = "";
		if(numOfAttendees > 3) {
			attendeesLink = '<a id="at_attendees_list_link_' + key.id + '" href="#">Show all ' + numOfAttendees + '</a>';
		}
		else {
			attendeesLink = '<p></p>';
		}
				
		var fullDesc = key.description;
		//var desc = shortDescriptionToLines(fullDesc);
		var rating = (parseInt(key.pluses) - parseInt(key.minuses));
		
		
		//googleImgSearch(key.title, tooltipImgSrchComplete(key.id));
		
		$('#accordion1').append('<h3 id="acc0_h3_attraction_' + key.id + '"><a href="#">' + key.title + '</a></h3>' + 								
								'<div id="acc0_div_attraction_' + key.id + '">' + 
									'<p>' +
										'<table  cellpadding="10">' +
										'<colgroup width="260"></colgroup>' +
										'<colgroup width="50"></colgroup>' +
											'<tr>' +
												'<td title="' + fullDesc + '" align="left" valign="top">' + fullDesc + '</td>' +
												'<td>' +
													'<div align="center"><input type="button" id="at_rateAdd' + key.id + '" name="rateAdd" class="plusButton" value="+"/></div>' +
													'<div id="at_attrRating' + key.id + '" align="center"><h2>' + rating + '</h2></div>' +
													'<div align="center"><input type="button" id="at_rateSub' + key.id + '" name="rateSub" class="minusButton" value="-"/></div>' +
												'</td>' +
											'</tr>'+
										'</table>' +
										'<table cellpadding="10">' +
											'<tr id="short_attendees_list_'+key.id+'">' +
											'</tr>' +
											//'<tr><td><br/></td></tr>' +
											'<tr>' +
												'<td width="131">' + attendeesLink + '</td>' +	
											'</tr>' +
											'<tr style="margin-top: 5px">' +
												'<td width="131">' +
													'<a id="at_showMoreDetailsLink' + key.id + '" href="#">Show more details...</a>' + 
												'</td>' +
											'</tr>' +
										'</table>' +
									'</p>' +
								'</div>');
		
		$("#at_showMoreDetailsLink" + key.id).button();
		/**List attendees in short description*/
		createShortAttractionAttendees(key.id, attendees);
		/**Set listeners for attraction's details (inner html)*/
		addingAccordion1ElementListeners(key.id, attendees);

	}
	
	
	
	function shortDescriptionToLines(desc) {
		var shortDesc = "";
		var temp =  desc;
		//shortning the description to fill in the accordion row
		if(temp.length > 72) {
			temp = temp.substring(0,72) + '...';
		}
		//breaking the short description into lines (up to 3).
		while(temp.length > 0) {
			if(temp.length > 25) {
				shortDesc = shortDesc + temp.substring(0,25) + '</br>';
				temp = temp.substring(26,temp.length);
			}
			else {
				shortDesc = shortDesc + temp;
				temp = "";
			}				
		}
		return shortDesc;
	}
	
	function createShortAttractionAttendees(id, attendees) {

		var numOfAttendees = attendees.length;
		var loopArray = (numOfAttendees < 3) ? numOfAttendees : 3;
		for(var i=0; i < loopArray; i++) {
			var attendee = attendees[i];
			debugAlert("attendee " + attendee + " image is added");
			FB.api( 
					{ 
						method: 'fql.query', 
						query: 'SELECT uid,profile_url,pic_square,first_name,last_name FROM user WHERE uid='+ attendee
					}, 

					function(response) {
						debugAlert("in createShortAttractionAttendees response, attendee=" + response[0].uid);
						var picLink = '<a href=# id="short_attendee_link_' + id + '_' + response[0].uid + '"' +
										' title="' + response[0].first_name + ' ' + response[0].last_name + '"><img src=' + response[0].pic_square + 
										' width="37" height="37" /></a>';
						if(i < (loopArray - 1)) {
							picLink = picLink + '<p width="3"></p>';
						}
						$("#short_attendees_list_" + id).append(picLink);
						shortAttractionAttendeesListener(id, response[0].uid);
					}  
			); 
		}  
	}
	
	function shortAttractionAttendeesListener(id, attendee) {
		debugAlert("shortAttractionAttendeesListener called while attendee=" + attendee + "; id=" + id);
		$("#short_attendee_link_" + id + "_" + attendee).data("attendee", attendee);
		$("#short_attendee_link_" + id + "_" + attendee).live('click', function() {
			var inner_attendee = $(this).data("attendee");
			debugAlert("in short_attendee_link_" + inner_attendee);
			getUserProfile(displayAttendeeProfile, inner_attendee);
			return false;
		});									  
	}
	
	function addingAccordion1ElementListeners(id, attendees) {
		
		$("#at_showMoreDetailsLink" + id).data("attrId", id).click(function() {
			var attrId = $(this).data("attrId");
			debugAlert("Attraction " + attrId + " showMoreDetails clicked!");
			getAttractionById(attrId);
		});
		
		$("#at_attendButton" + id).data("attrId", id).click(function() {
			var attrId = $(this).data("attrId");
			attendDialog(attrId , reloadAttrsOrStknsView);
		});
		
		$("#at_attendees_list_link_" + id).data("attrId", id).data("attendees", attendees).click(function() {
			var attrId = $(this).data("attrId");
			var attrAttendees = $(this).data("attendees"); 
			debugAlert("in attendees_list_link_" +  attrId);
			debugAlert("calling tr_showAttendees with: " + attrAttendees);
			tr_showAttendees(attrAttendees,true);
		});
		
		$("#at_rateAdd" + id).data("attrId", id).click(function() {
			var attrId = $(this).data("attrId");
			debugAlert("adding plus to attraction: " + attrId);
			AttractionAction("addPlusToAttraction", updateShortAttractionRating,attrId);
		});
		
		$("at_#rateSub" + id).data("attrId", id).click(function() {
			var attrId = $(this).data("attrId");
			debugAlert("adding minus to attraction: " + attrId);
			AttractionAction("addMinusToAttraction", updateShortAttractionRating, attrId);
		});
	}
	
	
	
	
/*	function gotoUserFBProfile(attendeeID) {
		FB.api({
			method: 'fql.query',
			query: 'SELECT profile_url FROM user WHERE uid=' + attendeeID
		}, 
		function(response) {
			$("#goToFBProfile").click(response[0].profile_url);
		});
	}
	
	
	function getProfilePicForAnotherAttendee(attendeeID) {
		FB.api({
			method: 'fql.query',
			query: 'SELECT pic_square FROM user WHERE uid=' + attendeeID
		}, 
		function(response) {
			$("#anotherAttendeeProfilePicture" + attendeeID).html('<img src="'+response[0].pic_square+'" height="50" width="50" />');
		});
	}
	*/
	
	
	function displayAttendeeProfile(userJ){
		debugAlert("in displayAttendeeProfile");
		$("#attendee_profile").html('<table width="300">' +
									'<tr height="110">' +
										'<td width="100">' +
											'<div id="anotherAttendeeProfilePicture"' + userJ.id + '><img src="https://graph.facebook.com/' + userJ.id + '/picture?type=normal" width="100" /></div>' +
										'</td>' +
										'<td width="16">' +
											' ' +
										'</td>' +
										'<td width="184" style="font:\'Comic Sans MS\', cursive; font-size:14px;">' +
											'<b>' + userJ.name + '</b>' +
										'</td>' +
									'</tr>' +
								'</table>' +
								'<table height="75" width="300" style="font-size:12px;">' +
									'<tr>' +
										'<td>' +
											'<b>Sex:</b>' +
										'</td>' +
										'<td>' +
											userJ.gender +
										'</td>' +
									'</tr>' +
									'<tr>' +
										'<td>' +
											'<b>Birthday:</b>' +
										'</td>' +
										'<td>' +
											userJ.birthday.substring(0,10) +
										'</td>' +
									'</tr>' +
									'<tr>' +
										'<td>' +
											'<b>Languages:</b>' +
										'</td>' +
										'<td>' +
											userJ.languages +
										'</td>' +
									'</tr>' +
								 '</table>' +
								 '<table width="300">' +
									'<tr>' +
										'<td height="27">' +
											'<b>About Me:</b>' +
										'</td>' +
									'</tr>' +
									'<tr style="overflow:auto">' +
										'<td height="80">' +
											'<p style="position:relative; left:3px; top:3px; padding:0 0 0 0">'+ userJ.info +'</p>' +
										'</td>' +
									'</tr>' +
									'<tr height="60">' +
									'<tr>' +
								'</table>' + 
								'<div style="float:right"><a href="http://www.facebook.com/' + userJ.id + '" target="_blank"><input type="button" id="goToFBProfile' + userJ.id + '" value="' + userJ.name + '\'s Facebook Profile" class="button_class"/></a></div>');
		
		//getProfilePicForAnotherAttendee(userJ.id);
		//$("#goToFBProfile").button();
		//gotoUserFBProfile(userJ.id);
		$("#attendee_profile").dialog("open");
	}
	
	/*THIS IS FOR TESTING-----------------------------------------*/
	/*$("#test").click(function() {test_list_attractions();});
	function test_list_attractions() {
		var jtest = {"size" : 5, "data" : [{"id":1,"longitude":3.0,"latitude":10.0,"title":"att0","description":"des att0","pastAttendees":[],"futureAttendees":[],"notScheduledYetAttendees":[],"pluses":0,"minuses":0}, {"id":4,"longitude":4.0,"latitude":15.0,"title":"att3","description":"des att3","pastAttendees":[],"futureAttendees":[],"notScheduledYetAttendees":[],"pluses":0,"minuses":0}, {"id":5,"longitude":30.0,"latitude":6.0,"title":"att4","description":"des att4","pastAttendees":[],"futureAttendees":[],"notScheduledYetAttendees":[],"pluses":0,"minuses":0}, {"id":2,"longitude":50.0,"latitude":200.0,"title":"att1","description":"des att1","pastAttendees":[],"futureAttendees":[],"notScheduledYetAttendees":[],"pluses":0,"minuses":0}, {"id":3,"longitude":50.0,"latitude":90.0,"title":"att2","description":"des att2","pastAttendees":[],"futureAttendees":[],"notScheduledYetAttendees":[],"pluses":0,"minuses":0} ]};
		list_attractions(jtest);
	}*/
	/*--------------------------------------------*/	



//	the function displays all the attractions that the current user attended to
	function getUserTrip(id) {
		var xmlhttp = createInitialRequest("getUserTrip",userID, "x-www-form-urlencoded","trip");
		xmlhttp.setRequestHeader("tripId", id);
		xmlhttp.onload = getOnReadyStateChangeFunction(showTrip, true, "failed to get user trip");
		xmlhttp.send();
	}
	
	function getAllUserTrips() {
		var xmlhttp = createInitialRequest("getAllUserTrips",userID.toString(), "x-www-form-urlencoded","trip");
		xmlhttp.onload = getOnReadyStateChangeFunction(doOnTab0, true,"failed to get user trips");
		xmlhttp.send();
	}
	
	function destroyUserTrip(tripId) {
		debugAlert("in destroyUserTrip with trip ID " + tripId);
		tripCandidateForDeletionID = -1;
		var xmlhttp = createInitialRequest("deleteTrip",userID, "x-www-form-urlencoded","trip");
		xmlhttp.setRequestHeader("tripId", tripId);
		xmlhttp.onload = getOnReadyStateChangeFunction(getAllUserTrips, false, "failed to delete trip");
		onInit = true;
		xmlhttp.send();
		
	}
	
	//	input: bounds of a location on the map;
	function getLocationStickyNotes(bounds) {
		var xmlhttp = createInitialRequest("getStickyNotesByBound",userID, "x-www-form-urlencoded","stickyNote");
		createAndSendLocationSearch(bounds, xmlhttp);
	}


//	input: bounds of a location on the map;
	function getLocationAttractions(bounds) {	
		var xmlhttp = createInitialRequest("getLocationAttractions",userID, "x-www-form-urlencoded","location");
		createAndSendLocationSearch(bounds, xmlhttp);
	}
	
	
	function createAndSendLocationSearch(bounds, xmlhttp) {
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();

		xmlhttp.setRequestHeader("latN", northEast.lat());
		xmlhttp.setRequestHeader("lonE", northEast.lng());
		xmlhttp.setRequestHeader("latS", southWest.lat());
		xmlhttp.setRequestHeader("lonW", southWest.lng());

		xmlhttp.onload = getOnReadyStateChangeFunction(doOnTab1, true, "failed to get search result");

		xmlhttp.send();
	}


	// get the user profile  stored on our server
	function getUserProfile(responseFunc,id){
		debugAlert("in getUserProfile, user id=" + id);
		var xmlhttp = createInitialRequest("getUserProfile", id, "x-www-form-urlencoded", "user");
		xmlhttp.onload = getOnReadyStateChangeFunction(responseFunc, true, "failed to get user profile");		
		xmlhttp.send();
	}

	//populate user edit profile dialog either from our db or from fb if it doesn't exist yet.
	//open dialog for editing
	function populateUserProfile(json) {		
		if (jQuery.isEmptyObject(json)) {
			debugAlert("the user dont have a Trippin' Out profile... creating one");
			tr_getProfileFromFB();
		}		
	}
	
	function populateUserProfileHelper(json) {
		$("#userName").html(json.name);
		$("#userProfilePic").attr('src', tr_getProfilePic());
		$("#userGender").val(json.gender);
		$("#userBirthday").val(json.birthday.substring(0,10));
		$("#userLanguages").val(json.languages);
		$("#userInfo").val(json.info);
		
		updateUserProfileStickyNotes(json.stickyNotes);

	}
	
	
	function updateUserProfileStickyNotes(stickyNotes) {
		var stknNum = (stickyNotes == null) ? 0 : stickyNotes.length;
		$("#myStickyNotes").children().remove();
		$("#myStickyNotes").html("");
		if (stknNum > 0) {
			$("#myStickyNotes").append('<br/><p>My Sticky Notes:</p><br/>');
			$("#myStickyNotes").append('<table>');
			$("#myStickyNotes").append('<tr><th><b>Title</b></th><th><b>From</b></th><th><b>To</b></th><th><b>Delete</b></th></tr>');
		}
		for(var i = 0; i < stknNum; i++) {
			var stkn = stickyNotes[i];
			$("#myStickyNotes").append('<tr>');
			
			if (stkn.start != null){
				$("#myStickyNotes").append('<td>' + stkn.title + "&nbsp;&nbsp;&nbsp;" + '</td>');
				$("#myStickyNotes").append('<td>' + stkn.start + "&nbsp;&nbsp;&nbsp;" + '</td>');
				$("#myStickyNotes").append('<td>' + stkn.end + "&nbsp;&nbsp;&nbsp;" + '</td>');
			}
			else {
				$("#myStickyNotes").append('<td colspan="3">' + stkn.title + '</td>');
			}
			$("#myStickyNotes").append('<td><input type="button" id="up_deleteStkn_' + stkn.id + '" name="deleteStkn" value="Delete"/></td></tr>');

			$("#up_deleteStkn_" + stkn.id).data("stknID", stkn.id).click(function() {
				var stknId =  $(this).data('stknID');
				debugAlert("in #up_deleteStkn_" + stknId + " button");
				deleteStickyNote(stknId);
			});
			
			$("#up_deleteStkn_" + stkn.id).button();
		}
		$("#myStickyNotes").append("</table>");
	}
	
	
	function deleteStickyNote(stickyNoteId) {
		var xmlhttp = createInitialRequest("deleteStickyNote", userID, "x-www-form-urlencoded","stickyNote");
		xmlhttp.setRequestHeader("stickyNoteId", stickyNoteId);	
		xmlhttp.onload = getOnReadyStateChangeFunction(updateUserProfileAndReloadStickyNotes, true, "failed to delete sticky note");
		debugAlert("sending request for deleteing sticky note " + stickyNoteId );
		xmlhttp.send();	
	}
	
	function updateUserProfileAndReloadStickyNotes(json) {
		debugAlert("in updateUserProfileAndReloadStickyNotes");
		updateUserProfileStickyNotes(json.data);
		if(!isAttractionView && (map.getZoom() > 2)) {
			removeOverlays();
			reloadAttrsOrStknsView(json);
		}		
	}
	
	
	function closeEditProfileDialog(json) {
		$("#edit_profile_form").dialog("close");
	}
	
	function updateUserProfile() {
		debugAlert("in updateUserProfile()");
		handleUserProfile("updateUserProfile", closeEditProfileDialog, "failed to update user profile");
	}
	
	
	function createUserProfile() {
		debugAlert("in createUserProfile()");
		handleUserProfile("createUserProfile", populateUserProfileHelper, "failed to create user profile");
	}
	
	function openUserProfileDialog(json) {
		populateUserProfileHelper(json);
		$("#edit_profile_form").dialog("open");
	}

	
	function handleUserProfile(action, func, errorMessage) {
		debugAlert("in handleUserProfile()");
		
		var xmlhttp = createInitialRequest(action, userID, "x-www-form-urlencoded","user");
		
		var json = "{\"name\" : " + "\"" + $("#userName").html()  + "\"" + ", " + 
		"\"gender\" : " + "\"" + $("#userGender").val() + "\"" + ", " +
		"\"birthday\" : " + "\"" + $("#userBirthday").val() + " 00:00\"" + ", " +
		"\"languages\" : " + "\"" + $("#userLanguages").val() + "\"" + ", " +
		"\"info\" : " + "\"" + $("#userInfo").val() + "\"}";
		
		debugAlert("json to send: " + json);
		
		xmlhttp.onload = getOnReadyStateChangeFunction(func, true, errorMessage);

		debugAlert("sending the request");
		xmlhttp.send(json);	
	}


	function tr_getAttractionByName(attName) {
		var xmlhttp = createInitialRequest("getAttractionByName",userID, "x-www-form-urlencoded","attraction");
		xmlhttp.setRequestHeader("attractionName", attName);

		xmlhttp.onload = getOnReadyStateChangeFunction(doOnTab1, true,
				"failed to get all attractions containing " + "\"" + attName + "\"");

		xmlhttp.send();
	}


	function tr_getGoogle(address) {
		geocoder.geocode( { 'address': address}, 
				function(results, status) {
			if(status == google.maps.GeocoderStatus.OK) {
				map.setCenter(results[0].geometry.location);

				var bounds = new google.maps.LatLngBounds();
				bounds = results[0].geometry.viewport;
				map.fitBounds(bounds);
				map.setZoom(map.getZoom() + 1);
				bounds = map.getBounds();
				
				map.setZoom(map.getZoom() + 1);
				bounds = map.getBounds();
				
				if(isAttractionView) {
					removeOverlays();
					getLocationAttractions(bounds);
				}
				else {
					getLocationStickyNotes(bounds);
				}
			} else {
				errorAlertPopup("Google Maps couldn't find query due to the following reason: " + status);
			}
		});
	}


//	input: json that contains a specific attraction
	function getAttractionById(id) {
		var xmlhttp = createInitialRequest("getAttractionById", userID,"x-www-form-urlencoded","attraction");
		var attId = id.toString();

		xmlhttp.setRequestHeader("attractionId", attId);	

		xmlhttp.onload = getOnReadyStateChangeFunction(showAttractionDetails, true, "failed to get the attraction " + attId);

		xmlhttp.send();
}
	
	
	$("#newTrip").click(function() {
		$("#create_update_trip").toggle(true);
		$("#showTrip").toggle(false);
	});
	$("#shareTrip").click(function() {
		debugAlert("Share Trip button clicked with trip id: " + userTrip.id);
		//shareTripRequestDialog();
		shareTripSendRequestToRecipients();
	});


	function replaceAll(txt, replace, with_this) {
		  return txt.replace(new RegExp(replace, 'g'),with_this);
		}
	/*
	function dateTimeForGoogleCalendar(var dateTime) {
		var res = dateTime.substring(6,10) + dateTime.substring(3,5) + dateTime.substring(0,2) + dateTime.substring(11,13) + dateTime.substring(14,16) + "00Z";
		return res;
	}
*/
	//show the planned trip on the trip_details div (all attractions etc..)
	function showTrip(json) {
		debugAlert("in showTrip");
		if(json.userId == userID) {
			$("#shareTrip").toggle(true);
		}
		else {
			$("#shareTrip").toggle(false);
		}
		
		userTrip.attrs = [];
		
		var startDate = createDateFromString(json.start);
		var endDate = createDateFromString(json.end);
		userTrip.id = json.id;	
		var dateTimeStart = createDateIncludeTimeFromString(json.start);
		var dateTimeEnd = createDateIncludeTimeFromString(json.end);
		userTrip.startDate = new Date(dateTimeStart.toString());
		userTrip.endDate = new Date(dateTimeEnd.toString());

		debugAlert("creating min max for datepicker");
		$("#schedAttrDateTime").datepicker("option", "minDate", new Date((userTrip.startDate).toString()));
		$("#schedAttrDateTime").datepicker("option", "maxDate", new Date((userTrip.endDate).toString()));
		

		$("#tripTitle").html(json.title);
		$("#tripFromDate").html("From: " + json.start);
		$("#tripToDate").html("To: " + json.end);
		
		$("#tripDaysList").children().remove();
		$("#attrListDays").children().remove();
		$("#tripDaysList").html('<td style="width: 170; min-width: 170" height= "10%" align="center" ><h4 style="color:#039; background:#69C">Unscheduled Attractions</h4></td>');
		$("#attrListDays").html('<td valign="top" height="90%" style="width: 170; min-width: 170"><div id ="unattended" class="tdScroll"><img src="images/tablefixer.gif" /></div></td>');
		
		debugAlert("creating notScheduledYetAttractions list");
		var unattendedAttr;
		var notScheduledYetAttractions = (json.notScheduledYetAttractions != null) ? json.notScheduledYetAttractions : [];
		for (var k=0; k < notScheduledYetAttractions.length; k++) {
			unattendedAttr = notScheduledYetAttractions[k];
			$("#unattended").append('<div id="st_unat_attraction_' + unattendedAttr.id + '" class="ui-widget-content1 ui-corner-all"><h4>'+unattendedAttr.title+'</h4><br/>'
												   +'<a id="tr_attr_unnattendedAttrDetailsLink' + unattendedAttr.id + '" href="#"><h6>Show more details</h6></a>'
												   +'</div>');
			//debugAlert("created div fot attr " +  unattendedAttr.id);
			$("#tr_attr_unnattendedAttrDetailsLink"+unattendedAttr.id).data('attrID', unattendedAttr.id).click(function() {
				debugAlert("Attraction " + unattendedAttr.id + " showMoreDetails clicked!");
				var attrID = $(this).data('attrID');
				getAttractionById(attrID);
			});
			
		}
		
		$("#unattended div").mouseout(function() {
			st_unattendMouseOverOut(this,"mouseout");
		});
		
		$("#unattended div").mouseover(function() {
			st_unattendMouseOverOut(this,"mouseover");
		});

		debugAlert("creating tripDaysList and attrListDays columns");
		var date = startDate;
		for (var i=0; i < json.numOfDays; i++) {
			debugAlert("creating day " + dateToString(date) + " with id attrInDay_" + dateToUnformattedString(date));
			$("#tripDaysList").append('<td align="center" class="ui-widget-content1 ui-corner-all" style="width: 170; min-width: 170">'+dateToString(date) + '</td>');
			$("#attrListDays").append('<td valign="top" height="90%" style="width: 170; min-width: 170"><div id="attrInDay_' + dateToUnformattedString(date) + '" class="tdScroll" ><img src="images/tablefixer.gif" /></div></td>');
			date.setDate(startDate.getDate()+1);
		}

		var scheduleAttractions = (json.scheduleAttractions != null) ? json.scheduleAttractions : [];
		debugAlert("building the scheduleAttractions. there are " + scheduleAttractions.length);
		var scheduleAttr;
		for (var j=0; j < scheduleAttractions.length; j++){
			
			scheduleAttr = scheduleAttractions[j];
			
			var strStartDate = scheduleAttr.startTime;
			var strEndDate = scheduleAttr.endTime;
			var attrDate = createDateFromString(strStartDate);
			
			var attrNumOfDay = checkNumDays(strStartDate, strEndDate);
			debugAlert("attr " + scheduleAttr.id + " has " + attrNumOfDay + " days");
			for(var day = 1; day <= attrNumOfDay; day++) {
				var from;
				var to;
				if(day == 1) {
					from = strStartDate.substring(11);
				}
				else {
					from = strStartDate;
				}
				
				if(day == attrNumOfDay) {
					to = strEndDate.substring(11);
				}
				else {
					to = strEndDate;
				}
				debugAlert("attr " + scheduleAttr.id + " " + from + " - " + to);
				
				var titleForGoogleCalander = replaceAll(scheduleAttr.title, ' ', '%20');
				var googleCalStart = strStartDate.substring(6,10) + strStartDate.substring(3,5) + strStartDate.substring(0,2) + "T" + strStartDate.substring(11,13) + strStartDate.substring(14,16) + "00Z";
				var googleCalEnd = strEndDate.substring(6,10) + strEndDate.substring(3,5) + strEndDate.substring(0,2) + "T" + strEndDate.substring(11,13) + strEndDate.substring(14,16) + "00Z";
				
				$("#attrInDay_" + dateToUnformattedString(attrDate)).append('<div id="st_sch_attraction_' + day + '_' + scheduleAttr.id + '" class="ui-widget-content ui-corner-all"><h4>' + scheduleAttr.title + '</h4>' +
						'<br/><h5>' + from + " - " + to + '</h5><br/>' +
						'<a href="#" id="tr_attr_scheduleAttrDetailsLink' + day + '_' + scheduleAttr.attrId + '"><h6>Show more details</h6></a><br/>' +
						'<a href="http://www.google.com/calendar/event?action=TEMPLATE&text=' + titleForGoogleCalander + '&dates=' + googleCalStart + "/" + googleCalEnd + '&details=&location=&trp=false&sprop=&sprop=name:" target="_blank"><img src="//www.google.com/calendar/images/ext/gc_button6.gif" alt="0" border="0"></a>' +
						'</div>');
				attrDate.setDate(attrDate.getDate() + 1);

				$("#tr_attr_scheduleAttrDetailsLink" + day + "_" + scheduleAttr.attrId).data('attrID', scheduleAttr.attrId).click(function() {
					debugAlert("Attraction " + scheduleAttr.attrId + " showMoreDetails clicked!");
					var attrID = $(this).data('attrID');
					getAttractionById(attrID);
				});

				$("#st_sch_attraction_" + day + "_" + scheduleAttr.id).mouseout(function() {
					st_scheduleMouseOverOut("mouseout", scheduleAttr.attrId);
				});

				$("#st_sch_attraction_" + day + "_" + scheduleAttr.id).mouseover(function() {
					st_scheduleMouseOverOut("mouseover", scheduleAttr.attrId);
				});
			}
		}
		
		userTrip.attrs = notScheduledYetAttractions.concat(scheduleAttractions);
		
		$("#ShowTripOnMap").click(function() {	
			if(userTrip.attrs.length > 0) {
				var maxlat = -1000;
				var maxlng = -1000;
				var minlat = 1000;
				var minlng = 1000;

				for (var i=0; i < userTrip.attrs.length; i++) {
					maxlat = Math.max(maxlat, userTrip.attrs[i].latitude);
					maxlng = Math.max(maxlng, userTrip.attrs[i].longitude);
					minlat = Math.min(minlat, userTrip.attrs[i].latitude);
					minlng = Math.min(maxlng, userTrip.attrs[i].longitude);						
				}

				var southWest = new google.maps.LatLng(minlat,minlng);
				var northEast = new google.maps.LatLng(maxlat,maxlng);
				var bounds = new google.maps.LatLngBounds(southWest,northEast);
				map.fitBounds(bounds);
				bounds = map.getBounds();
				getLocationAttractions(bounds);
			}
		});
	
		function st_unattendMouseOverOut (element,event) {
			for(var j = 1; j < attrStknListIDs.length; j++) {
				if(('st_unat_' + attrStknListIDs[j]) == element.id) {
					google.maps.event.trigger(markersArray[j], event);
					break;
				}
			}				
		}
		
		function st_scheduleMouseOverOut(event, id) {
			var index = $.inArray("attraction_" + id, attrStknListIDs);
			if(index >= 0) {
				google.maps.event.trigger(markersArray[index], event);
			}
		}
		
		if(onInit) {
			getAttractionIMayLike();
			getPeopleNearMe();
			getTripSharing();
			onInit = false;
		}
		
		debugAlert("toggling divs");
		$("#create_update_trip").toggle(false);
		$("#showTrip").toggle(true);
	}
	
	function checkNumDays(strStartTime, strEndTime) {
		var date = createDateFromString(strStartTime);
		var end = createDateFromString(strEndTime);
		var numOfDays = 1;
			while(date < end) {
				numOfDays++;
				date.setDate(date.getDate() + 1);
			}
		return numOfDays;
	}

	
	function dateToString(date) {
		var dd = date.getDate();
		var mm = date.getMonth()+1;//January is 0!
		var yyyy = date.getFullYear();
		if(dd<10) {
			dd = '0' + dd;
		}
		if(mm<10){
			mm = '0' + mm;
		}
		return (dd+'/'+mm+'/'+yyyy);
	}
	
	
	function dateToUnformattedString(date){
		var dd = date.getDate();
		var mm = date.getMonth() + 1;
		var yyyy = date.getFullYear();
		if(dd<10){dd='0'+dd}
		if(mm<10){mm='0'+mm}
		return (dd.toString()+mm+yyyy);
	}
	
	function createDateFromString(dateStr){
		var day = dateStr.substring(0,2);
		var month = (parseInt(dateStr.substring(3,5)) - 1) + "";
		var year = dateStr.substring(6,10);
		var date = new Date(year,month,day);
		return date;	
	}
	
	function createDateIncludeTimeFromString(dateStr) {
		var day = dateStr.substring(0,2);
		var month = (parseInt(dateStr.substring(3,5)) - 1) + "";
		var year = dateStr.substring(6,10);
		var hour = dateStr.substring(11,13);
		var min = dateStr.substring(14,16);
		var date = new Date(year,month,day, hour, min);
		return date;
	}


	/*-----------------------------------------------------HTTP Handling-------------------------------------------------------*/

//	create a XMLHttpRequest with the basic headers (action, userId)
	function createInitialRequest(action, userId, type, path) {
		debugAlert("in createInitialRequest");
		var xmlhttp;
		if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
			xmlhttp.open("POST",serverURL + "/" + path,true);
		}
		else
		{// code for IE6, IE5
			xmlhttp = new XDomainRequest();
			xmlhttp.open("POST",serverURL + "/" + path);
		}
		
		xmlhttp.setRequestHeader("Content-type", "application/" + type);
		xmlhttp.setRequestHeader("action", action);
		xmlhttp.setRequestHeader("userId", userId);
		return xmlhttp;
	}

	/**
	 * @param func - a function that recieved one argument - a json. the function is called with the response json.
	 * @param error - an error string to be displayed when an error is recieved.
	 * @return the function to be set as the xmlhttp.onreadystatechange.
	 **/
	function getOnReadyStateChangeFunction(responseFunc, reponseWithJson, error) {
		return function() {
			if(this.readyState == 4) {
				if (this.status == 200)	{
					if(responseFunc != null) {
						if(reponseWithJson == true) {
							debugAlert(this.responseText);
							var json =  eval('('+ this.responseText +')');
							responseFunc(json);
						}
						else {
							responseFunc();
						}					
					}
				}
				else {
					var responseText = this.responseText;
					var title = "<title>";
					var start = responseText.indexOf(title) + title.length;
					title = "</title>";
					var end = responseText.indexOf(title);
					var serverError = responseText.substring(start,end);
					errorAlertPopup(error + ":\n" + serverError);
				}
			}
		};
	}

	function userAlertPopup(message) {
		$("#userMessage").html(message);
		$("#userAlert").dialog("open");
	}

	function errorAlertPopup(error) {
		$("#errorMessage").html(error);
		$("#errorAlert").dialog("open");
	}


	/*--------------------------------------Facebook related scripts---------------------------------------------------*/

	window.fbAsyncInit = function() {
		FB.init({
			appId      : '253343158057648', // App ID
			//channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
			status     : true, // check login status
			cookie     : true, // enable cookies to allow the server to access the session
			oauth      : true, // enable OAuth 2.0
			xfbml      : true  // parse XFBML
		});

		getInitialData();	
		
		/**
		 * getInitialData() returns the current connected user's Facebook ID and than retrives all the user's trips
		 * if no user session is available, returns null
		 */
		function getInitialData() {
			debugAlert("in fb_script - getInitialData");
			FB.getLoginStatus(function(response) {  
				debugAlert("in fb_script - getInitialData: getting the response");
				if (response.authResponse) {  
					debugAlert("got authResponse");
					//getting current logged in user's id from session object  
					var id = response.authResponse["userID"];
					debugAlert("the user id " + id);
					userID = id;
					accessToken = response.authResponse["accessToken"];
					getUserProfile(populateUserProfile,userID);
					getAllUserTrips();
					onInit = true;
				}
				else {
					debugAlert("in getInitialData: failed to get the resp from facebook");
				}
			})
		}

	};

	
	
	// use this function to check whether the current user is 
	// friends with another user
	function isFriend(otherUserId) {
		areFriends = false;
		if (otherUserId != userID) {
		FB.api({
			method: 'fql.query',
			query: 'SELECT uid1, uid2 FROM friend WHERE uid1 = me() AND uid2 = ' + otherUserId
		}, 
		function(response) {
			//TODO: change contents of this action
			if (response.length == 0){
				areFriends = false;
			}
			else {
				areFriends = true;
			}
		});
		}
	}

/*
	function shareTripRequestDialog() {
		FB.ui({ method: 'apprequests', 
            message: 'Here is a new Requests dialog...'});
	}
*/
	function shareTripSendRequestToRecipients() {
		debugAlert("In shareTripSendRequestToRecipients");
		FB.ui({method: 'apprequests',
          message: 'Shared a Trip With You',
		  filters: ['app_users']
        }, shareTripRequestCallback);	
	}
	
	function shareTripRequestCallback(response) {
		var tripid = userTrip.id;
		for (var i = 0; i < response.to.length; i++) {
			debugAlert("shareTripCallBack for " + userTrip.id + " Called: " + response.to[i]);
			sendShareTripToServer(tripid, response.to[i]);
		}
	}
	
	function sendShareTripToServer(tripid, recepientid) {
		debugAlert("in sendShareTripToServer");
		var xmlhttp = createInitialRequest("sendTripSharingRequest", userID,"x-www-form-urlencoded","trip");
		
		debugAlert("creating headers for sendShareTripToServer");
		xmlhttp.setRequestHeader("tripId", tripid);	
		xmlhttp.setRequestHeader("shareWithId", recepientid);
		xmlhttp.onload = getOnReadyStateChangeFunction(null, false, "failed to share trip " + tripid + " with user " + recepientid);

		debugAlert("sending sendShareTripToServer");
		xmlhttp.send();
	}
		
	function tr_showAttendees(idArray, isFromAttr) {
		debugAlert("in fb_script - tr_showAttendees");
		if(isFromAttr) {
			$('#attendees_list').attr('title', 'Attending Attraction');
		}
		else {
			('#attendees_list').attr('title', 'Trip Shared With');
		}
		if (idArray.length == 0) {
			userAlertPopup("No one is currently attending this attraction.");
			return;
		}
		$("#attendees_list").children().remove();
		$("#attendees_list").html('<table>');
		for(var i=0; i < idArray.length; i++) {
			FB.api( 
					{ 
						method: 'fql.query', 
						query: 'SELECT uid,profile_url,pic_square,first_name,last_name,mutual_friend_count FROM user WHERE uid='+ idArray[i] 
					}, 

					function(response) {
						var attendeeId = response[0].uid;
						$("#attendees_list").append('<tr>' + 
														'<td><img src=' + response[0].pic_square + '/>' +
														'</td>' +
														'<td width="15"></td>' + 
														'<td valign="middle" ><a id="attendeeFromListProfile_' + attendeeId + '" href=# >' +
															response[0].first_name+ " " + response[0].last_name + '</a>' +
														'</td></tr>');
						
						if (attendeeId != userID){
							
							var mutualFriends = response[0].mutual_friend_count;
							$("#attendees_list").append('<tr height="5"><td></td></tr><tr><td colspan="2" align="left">');
							isFriend(attendeeId);
							if (areFriends == true) {
								$("#attendees_list").append('You are friends</td></tr>');
							}
							else if (mutualFriends == 1){
								$("#attendees_list").append('One mutual friend</td></tr>');
							}
							else {
								$("#attendees_list").append(mutualFriends + ' mutual friends</td></tr>');
							}
						}
						$("#attendees_list").append('<tr height="8"><td></td></tr>');
						attendeeFromListListener(attendeeId);
					}  
				); 
		}
		$("#attendees_list").append('</table>');
		$("#attendees_list").dialog("open");
	}

	function attendeeNameLink(idOfAttendee) {
		debugAlert("Clicked attendeeNameLink" + uid);
		getUserProfile(displayAttendeeProfile, uid);
	}
		
	function attendeeFromListListener(idOfAttendee) {
		debugAlert("attendeeFromListListener called while attendee=" + idOfAttendee);
		$("#attendeeFromListProfile_" + idOfAttendee).data('userid', idOfAttendee).live('click', function(){
			debugAlert("attendeeFromListProfile called");
			var uid = $(this).data('userid');
			debugAlert("Clicked attendeeFromListProfile_" + uid);
			getUserProfile(displayAttendeeProfile, uid);
			return false;
		});	
	}

function tr_getOwnerTripFB(userId){
		FB.api({
			method: 'fql.query',
			query: 'SELECT first_name,last_name,pic_square FROM user WHERE uid=' + userId 
		},
		function(response) {
			$("#tripOwnerProfilePicture" + userId).attr('src', response[0].pic_square);
			$("#tripOwnerName" + userId).html(response[0].first_name + " " + response[0].last_name);
		});
	}

function tr_getOwnerTripDescFB(userId){
	FB.api({
		method: 'fql.query',
		query: 'SELECT first_name,last_name,pic_square FROM user WHERE uid=' + userId 
	},
	function(response) {
		$("#tripOwnerProfilePictureDesc" + userId).attr('src', response[0].pic_square);
		$("#tripOwnerNameDesc" + userId).html(response[0].first_name + " " + response[0].last_name);
	});
}



function tr_getProfileNearMeFB(userId) {
		FB.api({
			method: 'fql.query',
			query: 'SELECT first_name,last_name,pic_square FROM user WHERE uid=' + userId 
		},
		function(response) {
			$("#userNearMeName" + userId).html(response[0].first_name + " " + response[0].last_name);
			$("#userNearMeProfilePicture" + userId).attr('src', response[0].pic_square);
		});	
	}
	
	function tr_getProfileFromFB() {
	FB.api({
		method: 'fql.query',
		query: 'SELECT first_name,last_name,pic_square,sex,birthday_date,languages,about_me FROM user WHERE uid=' + userID 
	}, 
	function(response) {
		$("#userName").html(response[0].first_name + " " + response[0].last_name);
		$("#userProfilePicture").attr('src', response[0].pic_square);
		$("#userGender").val(response[0].sex);
		var enBirthday = response[0].birthday_date;
		$("#userBirthday").val(enBirthday.substring(3,6) + enBirthday.substring(0,3) + enBirthday.substring(6,10));
		var languages = response[0].languages;
		$("#userLanguages").val("");
		for ( var i = 0; i < languages.length; i++) {
			$("#userLanguages").append(languages[i]);
			if (i != languages.length - 1)
				$("#userLanguages").append(",");
		}
		$("#userInfo").val(response[0].about_me);
		createUserProfile();
	});
}

function tr_getProfilePic() {
	FB.api({
		method: 'fql.query',
		query: 'SELECT pic_square FROM user WHERE uid=' + userID
	}, 
	function(response) {
		$("#userProfilePicture").attr('src', response[0].pic_square);
	});
}

// post a message to usere's wall, containing captionText and descriptionText
function postToFeed(captionText, descriptionText) {

    // calling the API ...
    var obj = {
      method: 'feed',
      link: 'http://apps.facebook.com/trippinout/',
      picture: 'http://trippinoutapp.appspot.com/images/icon_square.png',
      name: 'Trippin\' Out',
      caption: captionText,
      description: descriptionText
    };

    function callback(response) {
      document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
    }

    FB.ui(obj, callback);
  }


//get mutual friends of current user and another user and act according to results
function mutualFriends(otherUserId){
	debugAlert("in mutual friends");
	
	FB.api({
	            method: 'fql.query',
	            query: 'SELECT id FROM profile WHERE id IN (SELECT uid2 FROM friend WHERE uid1=me())'
	          },
	          function(response) {
	            $.each(response, function(json) {
	                console.info(response[json].id);
	                        FB.api(
	                          {
	                            method: 'friends.getMutualFriends',
	                            target_uid: otherUserId
	                          },
	                          function(response) {
	                        	//TODO: change here! 
	                            debugAlert(response);
	                          }
	                          );
	                return false;
	            });

	          }
	        );
}



//	Load the SDK Asynchronously
	(function(d) {
		var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
		js = d.createElement('script'); js.id = id; js.async = true;
		js.src = "//connect.facebook.net/en_US/all.js";
		d.getElementsByTagName('head')[0].appendChild(js);
	}(document));


	/*--------------------------------------for debug---------------------------------------------------*/

	function debugAlert(message) {
		if(DEBUG) {
			alert(message);
		}
	}

});
